//商品自动生成设置
import CommonModal from "@/components/CommonModal";
import CommonLoading from "@/components/CommonLoading";
import { useEffect, useState } from "react";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { Popover, Form, Drawer, Button, Select, Switch, Row, Col, Space } from "antd";
import { message } from "antd";
import Iconfont from "@/components/IconFont";
import CommonTable from "@/components/CommonTable";
import FilterRuleModal from "./FilterRuleModal";
import { getOrderRulesOp, changeRuleStatus, saveRuleConfigs } from "./service";
import { isEmpty } from "lodash";
import AntdFormWarp from "@/components/AntdFormWarp";
import CommonSelect from "@/pages/OrderModule/common/components/CommonSelect";
import CommonDrawer from '@/components/CommonDrawer';

const { Option } = Select;

const options = [
	{ label: "按原始编码生成", value: "original-code" },
	{ label: "按店铺款式编码+颜色规格", value: "spu-spec" },
	{ label: "按原始编码+颜色规格", value: "original-code-spec" },
	{ label: "按原始编码+平台skuid", value: "original-code-id" }
];

const connectOptions = [
	{ label: "-", value: "-" },
	{ label: "/", value: "/" },
	{ label: "无连接符", value: "无连接符" }
];

//字段名称/过滤规则
const fieldNameMap = {
	SKU_NAME: "商品名称",
	SPU_CODE: "款式编码",
	SKU_CODE: "商品编码",
	COLOR_SPECIFICATIONS: "颜色规格"
};

/** 商品自动生成设置 */
function EncodeSetting(props) {
	const { onCancel: handleCancel } = props;
	const [isOk, setIsOk] = useState(false);
	const [loading, setLoading] = useState(false);
	const [open, setOpen] = useState(false);
	const [visible, setVisible] = useState(false);
	const [data, setData] = useState([]);
	const [recordData, setRecordData] = useState({});

	const [form] = Form.useForm();

	//问号以及对应文案展示
	const iconTextRender = text => {
		return (
			<Popover content={<div style={{ width: "300px" }}>{text}</div>}>
				<div>
					<Iconfont type="iconwenhao1" />
				</div>
			</Popover>
		);
	};

	const columns = [
		{
			title: "字段名称/过滤规则",
			dataIndex: "fieldName",
			key: "fieldName",
			width: 180,
			render: text => <span>{fieldNameMap[text]}</span>
		},
		{
			title: "过滤符号及中间内容",
			dataIndex: "symbolMiddleShowContent",
			key: "symbolMiddleShowContent",
			width: 160,
			render: text => {
				return <span>{text && Array.isArray(text) && text.join(",")}</span>;
			}
		},
		{
			title: (
				<div style={{ display: "flex" }}>
					<span>关键字过滤</span>
					{iconTextRender("关键词从左至右排列进行优先级过滤")}
				</div>
			),
			dataIndex: "keyword",
			key: "keyword",
			width: 110,
			render(text) {
				return <>{text ? text.join(",") : ""}</>;
			}
		},
		{
			title: (
				<div style={{ display: "flex" }}>
					<span>过滤符号后内容</span>
					{iconTextRender("字符后所有的内容都将被截去（包含字符本身，符号不区分中英文）")}
				</div>
			),
			dataIndex: "symbolAfterContent",
			key: "symbolAfterContent",
			width: 140
		},
		{
			title: "是否开启",
			dataIndex: "status",
			key: "status",
			width: 100,
			render(text, record) {
				return (
					<Switch
						checkedChildren="开启"
						unCheckedChildren="关闭"
						size="large"
						checked={text == 1}
						onClick={e => handleSwitch(e, record)}
					/>
				);
			}
		},
		{
			title: "操作",
			dataIndex: "id",
			key: "id",
			width: 80,
			render: (_, record) => (
				<div className="opera-span-common" style={{ display: "felx", alignItems: "center" }}>
					<Button type="link" onClick={() => handleEdit(record)}>
						编辑
					</Button>
				</div>
			)
		}
	];

	useEffect(() => {
		setOpen(true);
		handleGetOrderRulesOp();
	}, []);

	useEffect(() => {
		if (!isEmpty(data)) {
			form.resetFields();
		}
	}, [data]);

	//点击编辑
	const handleEdit = record => {
		setVisible(true);
		setRecordData(record);
	};

	const onOk = () => {
		form.validateFields().then(val => {
			handleSubmit(val);
		});
	};

	//开关切换
	const handleSwitch = async (e, record) => {
		setLoading(true);
		const { success } = await changeRuleStatus({
			id: record.id,
			status: e ? "1" : "0"
		});
		if (success) {
			handleGetOrderRulesOp();
		}
		setLoading(false);
	};

	//查询详情
	const handleGetOrderRulesOp = async () => {
		setLoading(true);
		const { success, data = {} } = await getOrderRulesOp();
		setLoading(false);
		if (success) {
			setData(data);
		}
	};

	//点击确定
	const handleSubmit = async val => {
		setLoading(true);
		const { success, msg = "" } = await saveRuleConfigs({
			generateCodeRulesConfigVO: { ...val, connector: val.connector == "无连接符" ? "" : val.connector },
			platformGoodsFieldsFilterRules: data.platformGoodsFieldsFilterRules,
			systemGoodsFieldsFilterRules: data.systemGoodsFieldsFilterRules
		});
		setLoading(false);
		if (success) {
			message.success(msg);
			// setIsOk(true);
			// setOpen(false);
			handleCancel();
		}
	};

	const onCancel = () => {
		setOpen(false);
	};

	//底部按钮渲染
	const footerRender = () => {
		return (
			<div style={{ textAlign: "right" }}>
				<Button style={{ marginRight: "16px" }} onClick={() => handleCancel()}>
					取消
				</Button>
				<Button
					onClick={() => {
						onOk();
					}}
					type="primary"
				>
					确认
				</Button>
			</div>
		);
	};

	//表格
	const tableProps1 = {
		data: data?.platformGoodsFieldsFilterRules,
		columns,
		size: "small",
		handleRowKey(record) {
			return record.id;
		},
		scroll: { y: 300 }
	};

	const tableProps2 = {
		data: data?.systemGoodsFieldsFilterRules,
		columns,
		size: "small",
		handleRowKey(record) {
			return record.id;
		},
		scroll: { y: 300 }
	};

	//过滤规则设置
	const FilterRuleModalProps = {
		item: recordData,
		handleCancel() {
			setVisible(false);
			setRecordData({});
		},
		handleOk() {
			setVisible(false);
			setRecordData({});
			handleGetOrderRulesOp();
		}
	};

	const handleCreateSysGoodsActive = (e) => {
		form.validateFields().then(async (val) => {
			setLoading(true);
			const { success } = await saveRuleConfigs({
				generateCodeRulesConfigVO: { ...val, connector: val.connector == "无连接符" ? "" : val.connector, createSysGoodsActive: e ? 1 : 0 },
				platformGoodsFieldsFilterRules: data.platformGoodsFieldsFilterRules,
				systemGoodsFieldsFilterRules: data.systemGoodsFieldsFilterRules
			});
			setLoading(false);
			if (success) {
				handleGetOrderRulesOp();
			}
		});
	}

	return (
		<CommonDrawer
			title="商品自动生成设置"
			width="1000px"
			open={open}
			onClose={handleCancel}
			onOk={onOk}
			okText="保存"
			onCancel={onCancel}
			footer={footerRender()}
		>
			<SubTitle
				symbol
				as="s2"
				title={
					<div style={{ display: "flex" }}>
						一、商品编码生成规则
						{iconTextRender(
							"店铺商品编码和系统商品编码会根根据此处规则自动生成。根据过滤后的字段进行生成，店铺商品编码和系统商品编码始终保持一致连接符用于您不同字段之间的连接展示，例如选择原始编码+规格时，连接符选用“-”，您的店铺商品编码会根据原始编码和规格生成，再生成系统商品编码，店铺商品编码以此与系统商品编码形成绑定关系。如：原始商品编码为A，颜色规格为红色;L，店铺商品编码和系统商品编码为“A-红色;L”，店铺原始商品编码还是A"
						)}
					</div>
				}
				wrapStyle={{ marginBottom: 16 }}
			/>
			<Form
				form={form}
				className="new-search-form-style"
				onFinish={() => {}}
				name="express-warning-search-form"
				style={{
					display: 'block'
				}}
				initialValues={{
					...data.generateCodeRulesConfigVO,
					connector:
						data.generateCodeRulesConfigVO && data.generateCodeRulesConfigVO?.connector == ""
							? "无连接符"
							: data.generateCodeRulesConfigVO?.connector,
					createSysGoodsActive: data.generateCodeRulesConfigVO?.createSysGoodsActive ?? 1,
				}}
			>
				<Row gutter={[16, 16]}>
					<Col span={8} styl>
						<AntdFormWarp>
							<Form.Item label="" name="generateRule" rules={[{ required: true }]}>
								<CommonSelect aria-required allowClear placeholder="请选择生成规则">
									{options.map(item => (
										<Option key={item.value}>{item.label}</Option>
									))}
								</CommonSelect>
							</Form.Item>
						</AntdFormWarp>
					</Col>
					<Col span={8}>
						<AntdFormWarp>
							<Form.Item label="" name="connector" rules={[{ required: true }]}>
								<CommonSelect aria-required allowClear placeholder="连接符">
									{connectOptions.map(item => (
										<Option key={item.value}>{item.label}</Option>
									))}
								</CommonSelect>
							</Form.Item>
						</AntdFormWarp>
					</Col>
				</Row>
				<Space align="end">
					<Form.Item
						label="商品编码为空时不生成系统商品"
						name="createSysGoodsActive"
						valuePropName="checked"
						style={{ marginBottom: 0 }}
					>
						<Switch onClick={handleCreateSysGoodsActive} />
					</Form.Item>
					{iconTextRender(
						<>
							<div>关闭：根据规则店铺商品编码为空时，按 skuid 填充编码自动生成系统商品</div>
							<div>开启：根据规则店铺商品编码为空，不会自动生成系统商品</div>
						</>
					)}
				</Space>
			</Form>
			<SubTitle
				symbol
				as="s2"
				title={
					<div style={{ display: "flex" }}>
						二、生成店铺商品字段过滤
						{iconTextRender("商品及订单同步店铺商品时，erp内店铺商品资料自动过滤内容，该设置对【商品】和【订单】模块均有效")}
					</div>
				}
				wrapStyle={{ marginBottom: 16, marginTop: "16px" }}
			/>
			<CommonTable {...tableProps1} />
			<SubTitle
				symbol
				as="s2"
				title={
					<div style={{ display: "flex" }}>
						三、生成系统商品字段过滤
						{iconTextRender("根据店铺商品信息生成系统商品时，过滤掉系统商品资料中的信息")}
					</div>
				}
				wrapStyle={{ marginBottom: 16, marginTop: "16px" }}
			/>
			<CommonTable {...tableProps2} />
			{visible && <FilterRuleModal {...FilterRuleModalProps} />}
			<CommonLoading loading={loading} />
		</CommonDrawer>
	);
}

export default EncodeSetting;
